package com.zdy.today.api;

import android.content.Context;

import com.orhanobut.logger.Logger;
import com.zdy.today.Constant;
import com.zdy.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zdy on 2016/9/18.
 */
public class AskService {
    private static OkHttpClient client;
    private static Retrofit retrofit;
    private static OkHttpClient client1;
    private static Retrofit retrofit1;
    //https
    private static OkHttpClient getClient(Context context) {
        if (client == null) {
            X509TrustManager trustManager;
            SSLSocketFactory sslSocketFactory;
            try {
                trustManager = trustManagerForCertificates(new Buffer()
//                        .writeUtf8(Constant.CER_RINPOCHE)//https证书
                        .inputStream());
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{trustManager}, null);
                sslSocketFactory = sslContext.getSocketFactory();
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }
            File httpCacheDirectory = new File(context.getCacheDir(), "cache_file");
            Logger.d(httpCacheDirectory.exists());
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            client = new OkHttpClient.Builder().retryOnConnectionFailure(true)
                    .addInterceptor(httpLoggingInterceptor).sslSocketFactory(sslSocketFactory, trustManager)
//                    .addNetworkInterceptor(new StethoInterceptor())
                    .cache(new Cache(httpCacheDirectory, 500 * 1024 * 1024)) // 500 MB
                    .addInterceptor(chain -> {
                        Request request = chain.request();
                        if (Utils.isNetworkAvailable(context)) {
                            request = request.newBuilder().header("Cache-Control", "public, max-age=" + 0)
                                    .build();
                        } else {
                            request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7*100)//没有网络的情况下缓存一周
                                    .build();
                        }
                        return chain.proceed(request);
                    }).build();
        }
        return client;
    }
    //http
    private static OkHttpClient getClient1(Context context) {
        if (client1 == null) {
            File httpCacheDirectory = new File(context.getCacheDir(), "cache_file");
            Logger.d(httpCacheDirectory.exists());
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            client1 = new OkHttpClient.Builder().retryOnConnectionFailure(true)
                    .addInterceptor(httpLoggingInterceptor)
//                    .addNetworkInterceptor(new StethoInterceptor())
                    .cache(new Cache(httpCacheDirectory, 50 * 1024 * 1024)) // 50 MB
                    .addInterceptor(chain -> {
                        Request request = chain.request();
                        if (Utils.isNetworkAvailable(context)) {
                            request = request.newBuilder().header("Cache-Control", "public, max-age=" + 0)
                                    .build();
                        } else {
                            request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7)//没有网络的情况下缓存一周
                                    .build();
                        }
                        return chain.proceed(request);
                    }).build();
        }
        return client1;
    }

    private static Retrofit getRetrofit(Context context) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(Constant.BASE_URL)
                    .client(getClient(context))
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }
    private static Retrofit getRetrofit1(Context context) {
        if (retrofit1 == null) {
            retrofit1 = new Retrofit.Builder()
                    .baseUrl(Constant.BASE_URL)
                    .client(getClient1(context))
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        }
        return retrofit1;
    }

    public static AskApi createDemoService(Context context) {
        return getRetrofit(context).create(AskApi.class);
    }
    public static AskApi createDemoService1(Context context) {
        return getRetrofit1(context).create(AskApi.class);
    }

    private static X509TrustManager trustManagerForCertificates(InputStream in)
            throws GeneralSecurityException {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
        if (certificates.isEmpty()) {
//            throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        }

        // Put the certificates a key store.
        char[] password = "zhang123".toCharArray(); // Any password will work.
        KeyStore keyStore = newEmptyKeyStore(password);
        int index = 0;
        for (Certificate certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificate);
        }

        // Use it to build an X509 trust manager.
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }
        return (X509TrustManager) trustManagers[0];
    }

    private static KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream in = null; // By convention, 'null' creates an empty key store.
            keyStore.load(in, password);
            return keyStore;
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }

}
